var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const connectDB = require('./config/db');
const cors = require('cors'); // 新增：引入cors模块
connectDB();
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var workOrdersRouter = require('./routes/workOrders');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(cors()); // 新增：启用cors中间件（默认允许所有源）
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 新增：请求响应日志中间件
app.use((req, res, next) => {
  const startTime = Date.now();
  const { method, originalUrl, query, body } = req;
  
  // 记录请求信息（方法、URL、查询参数、请求体）
  console.log(`[请求] 方法: ${method}, URL: ${originalUrl}, 查询参数: ${JSON.stringify(query)}, 请求体: ${JSON.stringify(body)}`);

  // 重写 res.json 方法以捕获响应内容
  const originalJson = res.json;
  res.json = function (responseBody) {
    res.locals.responseBody = responseBody; // 存储响应内容
    originalJson.call(this, responseBody);
  };

  // 响应完成后记录状态码、耗时和响应内容
  res.on('finish', () => {
    const duration = Date.now() - startTime;
    const { statusCode } = res;
    const responseBody = res.locals.responseBody || '';
    console.log(`[响应] 状态码: ${statusCode}, 耗时: ${duration}ms, 响应内容: ${JSON.stringify(responseBody)}`);
  });

  next();
});

app.use('/', indexRouter);       // 根路径由 index.js 处理
app.use('/users', usersRouter);  // 所有 /users 开头的路径由 users.js 处理
app.use('/workOrders', workOrdersRouter); // 新增工单路由

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
